﻿//-----------------------------------------------------------------------
// <copyright file="MetadataEditor.cs" company="Microsoft Corporation">
//     Copyright Microsoft Corporation. All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) This is sample code only, do not use in production environments.
// </copyright>
//-----------------------------------------------------------------------
namespace vsarFlightPlan.ViewModels
{
    using System;
    using System.Collections.ObjectModel;
    using System.Threading.Tasks;
    using System.Windows.Input;
    using VisualStudioOnlineOData;
    using VisualStudioOnlineOData.Models;
    using VisualStudioOnlineOData.Utilities;
    using vsarFlightPlan.Utilities;
    using Windows.Storage;
    using Windows.UI.Popups;

    /// <summary>
    ///
    /// </summary>
    internal class MetadataEditor : ViewModelBase
    {
        private DetailedViewItem _targetItem;
        private ApplicationDataContainer settings;

        /// <summary>
        /// Initializes a new instance of the <see cref="MetadataEditor"/> class.
        /// </summary>
        public MetadataEditor(DetailedViewItem item)
        {
            TargetItem = item;
            this.settings = SettingUtils.SettingsContainer();
            DetailedItems = new ObservableCollection<DetailedViewItem>();

            UpdateMetadata = new Command(async () => { await OnUpdateMetadata(item); });
            ToggleHideStatus = new Command(() => OnToggleHideStatus(item));
        }

        public ICommand ToggleHideStatus { get; private set; }

        /// <summary>
        /// Gets the detailed items.
        /// </summary>
        /// <value>
        /// The detailed items.
        /// </value>
        public ObservableCollection<DetailedViewItem> DetailedItems { get; private set; }

        /// <summary>
        /// Gets or sets the item which will be editted.
        /// </summary>
        /// <value>
        /// The selected item.
        /// </value>
        public DetailedViewItem TargetItem
        {
            get
            {
                return _targetItem;
            }
            set
            {
                this.UpdateProperty(ref _targetItem, value);
            }
        }

        /// <summary>
        /// Gets the update metadata.
        /// </summary>
        /// <value>
        /// The update metadata.
        /// </value>
        public ICommand UpdateMetadata { get; private set; }

        /// <summary>
        /// Gets the credentials.
        /// </summary>
        /// <returns></returns>
        private Credentials GetCredentials()
        {
            if (settings == null)
            {
                return null;
            }

            var account = settings.Read<string>("account", null);
            if (account == null)
            {
                return null;
            }

            var username = settings.Read<string>("username", null);
            var password = settings.Read<string>("password", null);
            return new Credentials(account, username, password);
        }

        private void OnToggleHideStatus(object item)
        {
            var detailedItem = item as DetailedViewItem;
            detailedItem.Hidden = !detailedItem.Hidden;
            SettingUtils.HiddenItemsContainer().Values[detailedItem.Id] = detailedItem.Hidden;
        }

        private async Task OnUpdateMetadata(object item)
        {
            var detailedItem = item as DetailedViewItem;
            UpdateMetaDataState(detailedItem);
            var result = WorkItemProperties.UpdatedDescription(detailedItem.Description, detailedItem);
            var success = await WorkItems.Update(detailedItem.Id, GetCredentials(), detailedItem.State, result);

            if (!success)
            {
                await new MessageDialog("There was an issue updating the workitem. Please try again.").ShowAsync();
            }
        }

        private void UpdateMetaDataState(DetailedViewItem item)
        {
            if (item.Scheduled != DateTimeOffsetTools.Base() && item.Scheduled < DateTimeOffset.UtcNow)
            {
                if (item.Status == ProjectStatus.Landed)
                {
                    return;
                }

                item.Status = ProjectStatus.Delayed;
            }
        }
    }
}